﻿Public Class KhachHangDA
    Private cn As DatabaseConnect
    Private sql As String

    Public Sub New()
        cn = New DatabaseConnect()
    End Sub

    Public Function InUp(ByVal kh As KhachHangDT, ByVal flag As Boolean)
        Dim ma As String = kh.MaKH
        Dim ten As String = kh.TenKH
        Dim dienthoai As String = kh.DienThoai
        Dim diachi As String = kh.DiaChi
        Dim email As String = kh.Email
        Dim id As Integer = kh.ID
        '----------------------------------------------------'
        If flag = True Then
            sql = "INSERT INTO KhachHang(MaKH,hotenKH,dienthoai,diachi,email) VALUES('" + ma + "',N'" + ten + "','" + dienthoai + "',N'" + diachi + "','" + email + "')"
        Else
            sql = "UPDATE KhachHang SET hotenKH = N'" + ten + "', dienthoai = '" + dienthoai + "', diachi = N'" + diachi + "', email = '" + email + "' WHERE MaKH = '" + ma + "' "
        End If
        Return cn.Execute(sql)
    End Function

    Public Function Delete(ByVal kh As KhachHangDT)
        Dim id As Integer = kh.ID
        sql = "delete from KhachHang where Id = " & id & ""
        Return cn.Execute(sql)
    End Function

    Public Function GetData(ByVal dieukien As String) As List(Of KhachHangDT)
        Dim id As Integer
        Dim ma, ten, dienthoai, diachi, email As String
        Dim kh As KhachHangDT
        Dim list As New List(Of KhachHangDT)
        Dim dt As New DataTable
        dt = cn.GetData("SELECT * FROM KhachHang" + dieukien)

        For i As Integer = 0 To dt.Rows.Count() - 1
            id = Convert.ToInt32(dt.Rows(i)("Id"))
            ma = dt.Rows(i)("MaKH").ToString()
            ten = dt.Rows(i)("hotenKH").ToString()
            dienthoai = dt.Rows(i)("dienthoai").ToString()
            diachi = dt.Rows(i)("diachi").ToString()
            email = dt.Rows(i)("email").ToString()
            '-----'
            kh = New KhachHangDT(ma, ten, dienthoai, diachi, email, id)
            list.Add(kh)
        Next
        Return list
    End Function

    Function GetID() As Integer
        Dim dt As New DataTable
        Dim id As Integer
        dt = cn.GetData("SELECT * FROM KhachHang")
        If dt.Rows.Count > 0 Then
            id = Convert.ToInt32(dt.Rows(dt.Rows.Count - 1).Item("Id"))
        Else
            id = 1
        End If
        Return id
    End Function

    Public Function GetInserted() As String
        Dim dt As New DataTable
        Dim ma As String
        dt = cn.GetData("SELECT * FROM KhachHang")
        ma = dt.Rows(dt.Rows.Count - 1)("MaKH").ToString()
        Return ma
    End Function
End Class
